package com.tarena.lbs.content.dao.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.xiaoymin.knife4j.spring.configuration.Knife4jSetting;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.content.dao.mapper.ArticleMapper;
import com.tarena.lbs.content.dao.repository.ArticleRepository;
import com.tarena.lbs.content.pojo.param.ArticleActionParam;
import com.tarena.lbs.content.pojo.param.ArticleContentParam;
import com.tarena.lbs.content.pojo.query.ArticleQuery;
import com.tarena.lbs.content.pojo.vo.ArticleActionPageResultVO;
import com.tarena.lbs.content.pojo.vo.ArticleVO;
import com.tarena.lbs.user.api.UserApi;
import com.tarena.lbs.user.api.pojo.dto.AdminDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.*;

@Repository
@Slf4j
@DubboComponentScan(basePackages = "com.tarena.lbs.api")
public class ArticleRepositoryImpl implements ArticleRepository {
    @Autowired
    private ArticleMapper articleMapper;
    @DubboReference
    private UserApi userApi;
    @Autowired
    private Knife4jSetting knife4jSetting;

//    private UserApi userApi;
//


    @Override
    public PageResult<ArticleVO> pageList(ArticleQuery articleQuery) {
        log.debug("[持久层]处理分页查询文章,入参{}", articleQuery);
        //装配Wrapper
        QueryWrapper<ArticleVO> wrapper = new QueryWrapper<>();

        // 根据ArticleQuery条件动态构建查询条件
        if (articleQuery.getArticleTitle() != null && !articleQuery.getArticleTitle().isEmpty()) {
            wrapper.like("article_title", articleQuery.getArticleTitle());
        }
        if (articleQuery.getArticleCategoryId() != null) {
            wrapper.eq("article_category_id", articleQuery.getArticleCategoryId());
        }
        if (articleQuery.getArticleLabel() != null && !articleQuery.getArticleLabel().isEmpty()) {
            wrapper.like("article_label", articleQuery.getArticleLabel());
        }
        if (articleQuery.getArticleStatus() != null && !articleQuery.getArticleStatus().isEmpty()) {
            wrapper.in("article_status", articleQuery.getArticleStatus());
        }
        if (articleQuery.getSource() != null) {
            wrapper.eq("source", articleQuery.getSource());
        }
        if (articleQuery.getActivityId() != null) {
            wrapper.eq("activity_id", articleQuery.getActivityId());
        }
        if (articleQuery.getUserId() != null) {
            wrapper.eq("user_id", articleQuery.getUserId());
        }
        if (articleQuery.getUpdateStartTime() != null) {
            wrapper.ge("update_time", articleQuery.getUpdateStartTime());
        }
        if (articleQuery.getUpdateEndTime() != null) {
            wrapper.le("update_time", articleQuery.getUpdateEndTime());
        }

        //调用
        List<ArticleVO> resultList = articleMapper.selectList(null, wrapper);
        //转换为PageResult
        PageResult<ArticleVO> pageResult = new PageResult<>();
        pageResult.setObjects(resultList);
        pageResult.setPageNo(articleQuery.getPageNo());
        pageResult.setPageSize(articleQuery.getPageSize());
        pageResult.setTotal((long) 10);
        return pageResult;
    }

    @Override
    public int saveOrUpdate(ArticleContentParam param) throws BusinessException {
        log.debug("[持久层]处理文章保存/更新公共逻辑,入参{}", param);
        //转换为ArticleVO
        ArticleVO articleVO = new ArticleVO();
        BeanUtils.copyProperties(param, articleVO);
        //处理userId、userPic、userName、location、createTime、updateTime
        Date now = new Date();
        if (param.getId() == null) {
            articleVO.setCreateTime(now);
        }
        articleVO.setUpdateTime(now);
        // 获取当前登录用户信息
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        if (userPrinciple == null) {
            throw new BusinessException("402", "无法获取当前用户信息");
        }
        articleVO.setUserId(userPrinciple.getId());
        AdminDto adminDto;
        try {
            adminDto = userApi.getAdminById(userPrinciple.getId());
        } catch (Exception e) {
            log.error("远程调用 userApi.getAdminById 失败，userId={}", userPrinciple.getId(), e);
            throw new BusinessException("406", "获取用户信息失败");
        }

        if (adminDto == null) {
            throw new BusinessException("404", "未找到对应管理员信息");
        }

        articleVO.setUserPic(adminDto.getAccountPhone());
        articleVO.setUserName(adminDto.getNickname());

        // 判断是插入还是更新
        if (articleVO.getId() == null) {
            log.debug("[持久层]处理文章保存公共逻辑");
            return articleMapper.insert(articleVO);
        } else {
            log.debug("[持久层]处理文章更新公共逻辑");
            UpdateWrapper<ArticleVO> wrapper = new UpdateWrapper<>();
            wrapper.eq("id", articleVO.getId());
            return articleMapper.update(articleVO, wrapper);
        }
    }

    @Override
    public ArticleVO selectDetailById(String id) {
        log.debug("[持久层]处理文章详情查询,入参{}", id);
        return articleMapper.selectById(id);
    }

    @Override
    public int deleteById(String id) {
        log.debug("[持久层]处理文章删除,入参{}", id);
        return articleMapper.deleteById(id);
    }

    @Override
    public Set<String> articleLabels(ArticleQuery articleQuery) {
        log.debug("[持久层]处理文章标签集合,入参{}", articleQuery);
        String title = articleQuery.getArticleTitle();
        QueryWrapper wrapper = new QueryWrapper();
        if (title != null && !title.isEmpty()) {
            wrapper.eq("article_title", title);
        }
        List<ArticleVO> resultList = articleMapper.selectList(null, wrapper);
        Set<String> labels = new HashSet<>();
        for (ArticleVO articleVO : resultList) {
            if (articleVO.getArticleLabel() != null && !articleVO.getArticleLabel().isEmpty()) {
                labels.addAll(Arrays.asList(articleVO.getArticleLabel().split(",")));
            }
        }
        return labels;
    }

    @Override
    public int articleBehavior(ArticleActionParam param) {
        log.debug("[持久层]处理用户行为记录,入参{}", param);
        //TODO 远程带调用触达以实现,先打印日志
        log.debug("[持久层]----------处理用户行为记录");
        return 1;
    }

    @Override
    public ArticleActionPageResultVO getBehaviorLists(ArticleQuery query) {
        log.debug("[持久层]处理用户行为文章列表查询,入参{}", query);
        //TODO 远程带调用触达以实现,先打印日志
        log.debug("[持久层]----------处理用户行为文章列表查询");
        ArticleActionPageResultVO resultVO = new ArticleActionPageResultVO();
        return resultVO;
    }
}
